<?php

class EmbeddedAddressValidatorSchema extends sfValidatorSchema
{
  const OPTION_ALLOW_EMPTY = 'allow_empty';

  protected function configure ($options = array(), $messages = array())
  {
    $this->addOption(self::OPTION_ALLOW_EMPTY, false);
    $this->addMessage('street', 'Street is required');
    $this->addMessage('street_number', 'Street number is required');
    $this->addMessage('zip_code', 'Zip code number is required');
    $this->addMessage('city', 'City is required');
  }

  protected function doClean ($values)
  {
    $empty_forms = 0;
    $allow_empty_forms = $this->getOption(self::OPTION_ALLOW_EMPTY);
    
    $errorSchema = new sfValidatorErrorSchema($this);
    foreach ($values as $key => $value)
    {
      
      $localErrorSchema = new sfValidatorErrorSchema($this);
      
      if (! $value['street'] && ! $value['street_number'] && ! $value['zip_code'] && ! $value['city'])
      {
        if($allow_empty_forms == false || $empty_forms >= $allow_empty_forms) {
          unset($values[$key]);
        } else {
          $empty_forms++;
        }
      }
      else
      {
        if (! $value['street'])
        {
          $localErrorSchema->addError(new sfValidatorError($this, 'required'), 'street');
        }
        if (! $value['street_number'])
        {
          $localErrorSchema->addError(new sfValidatorError($this, 'required'), 'street_number');
        }
        if (! $value['zip_code'])
        {
          $localErrorSchema->addError(new sfValidatorError($this, 'required'), 'zip_code');
        }
        if (! $value['city'])
        {
          $localErrorSchema->addError(new sfValidatorError($this, 'required'), 'city');
        }
      }
      
      if (count($localErrorSchema))
      {
        $errorSchema->addError($localErrorSchema, (string) $key);
      }
    }
    
    if (count($errorSchema))
    {
      throw new sfValidatorErrorSchema($this, $errorSchema);
    }
    
    return $values;
  }
}